package work.zhengyun.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.zhengyun.demo.dao.PermissionDao;
import work.zhengyun.demo.dao.RolePermissionDao;
import work.zhengyun.demo.entity.Permission;
import work.zhengyun.demo.entity.Role;
import work.zhengyun.demo.entity.RolePermission;
import work.zhengyun.demo.entity.User;
import work.zhengyun.demo.service.PermissionService;
import work.zhengyun.demo.service.RoleService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhengyun
 * @date 2019/11/27 16:48
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionDao rolePermissionDao;
    @Autowired
    private PermissionDao permissionDao;
    /**
     * 通过 用户 获取 他拥有的所有权限名
     */
    @Override
    public Set<String> listPermissionName(User user) {
        Set<String> result = new HashSet<>();
        List<Role> roles = roleService.listRoleByUser(user);
        List<RolePermission> rolePermissions = new ArrayList<>();
        for (Role role : roles) {
            List<RolePermission> rps = rolePermissionDao.findListRolePermissionByRoleId(role.getId());
            rolePermissions.addAll(rps);
        }
        for (RolePermission rolePermission : rolePermissions) {
            Permission p = permissionDao.findByPrimaryKey(rolePermission.getPermissionId());
            result.add(p.getName());
        }
        return result;
    }
    @Override
    public List<Permission> listPermission() {
        return permissionDao.findAll();
    }
}
